package com.mapaoer.user.controller;

import com.mapaoer.user.dto.UpdateProfileDTO;
import com.mapaoer.user.entity.User;
import com.mapaoer.user.service.UserService;
import com.mapaoer.user.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;


/**
 * 用户控制器
 * 处理用户信息相关的API请求
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @GetMapping("/profile")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> getCurrentUserProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        return ResponseEntity.ok(ResponseResult.success(user));
    }

    /**
     * 更新用户资料
     * @param updateProfileDTO 更新信息
     * @return 更新结果
     */
    @PutMapping("/profile")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> updateUserProfile(@Valid @RequestBody UpdateProfileDTO updateProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        boolean result = userService.updateProfile(user.getId(), updateProfileDTO);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("资料更新成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("资料更新失败"));
        }
    }

    /**
     * 更新用户密码
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 更新结果
     */
    @PutMapping("/password")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> updatePassword(
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        boolean result = userService.updatePassword(user.getId(), oldPassword, newPassword);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("密码更新成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("旧密码错误"));
        }
    }

    /**
     * 获取用户信息（管理员）
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return ResponseEntity.ok(ResponseResult.success(user));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 禁用用户（管理员）
     * @param id 用户ID
     * @return 操作结果
     */
    @PutMapping("/{id}/disable")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> disableUser(@PathVariable Long id) {
        boolean result = userService.disableUser(id);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("用户已禁用"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 启用用户（管理员）
     * @param id 用户ID
     * @return 操作结果
     */
    @PutMapping("/{id}/enable")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult<?>> enableUser(@PathVariable Long id) {
        boolean result = userService.enableUser(id);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("用户已启用"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}